import redis
import json
import time

def monitor_redis():
    try:
        # 连接到Redis服务器
        redis_client = redis.Redis(
            host='www.v110.cc',
            port=6379,
            password='gR0gE9xX',
            decode_responses=True
        )
        
        # 测试连接
        redis_client.ping()
        print("成功连接到Redis服务器")
        
        # 创建发布/订阅对象
        pubsub = redis_client.pubsub()
        
        # 订阅控制频道
        pubsub.subscribe('motor_control')
        
        print("\n开始监听 motor_control 频道...")
        print("按 Ctrl+C 停止监听")
        
        # 持续监听消息
        for message in pubsub.listen():
            if message['type'] == 'message':
                try:
                    data = json.loads(message['data'])
                    direction = data.get('direction')
                    duration = data.get('duration')
                    print(f"\n收到新命令:")
                    print(f"时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
                    print(f"方向: {direction}")
                    print(f"持续时间: {duration}秒")
                except json.JSONDecodeError:
                    print(f"收到非JSON格式消息: {message['data']}")
                except Exception as e:
                    print(f"处理消息时出错: {e}")
            
    except redis.ConnectionError as e:
        print(f"Redis连接错误: {e}")
    except KeyboardInterrupt:
        print("\n停止监听")
    except Exception as e:
        print(f"发生错误: {e}")

if __name__ == "__main__":
    monitor_redis() 